package com.hsz.motion.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hsz.motion.MyApplication;
import com.hsz.motion.R;
import com.hsz.motion.commmon.bean.PathRecord;
import com.hsz.motion.commmon.bean.SportMotionRecord;
import com.hsz.motion.commmon.utils.DateUtils;
import com.hsz.motion.commmon.utils.LogUtils;
import com.hsz.motion.commmon.utils.MySp;
import com.hsz.motion.commmon.utils.UIHelper;
import com.hsz.motion.databinding.ActivityHomeBinding;
import com.hsz.motion.db.DataManager;
import com.hsz.motion.db.RealmHelper;
import com.hsz.motion.sport_motion.MotionUtils;
import com.hsz.motion.ui.BaseActivity;
import com.hsz.motion.ui.adapter.SportCalendarAdapter;
import com.hsz.motion.ui.weight.calendarview.custom.CustomWeekBar;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeActivity extends BaseActivity {

    private ActivityHomeBinding mBinding;
    /**
     * 上次点击返回键的时间
     */
    private long lastBackPressed;

    //上次点击返回键的时间
    public static final int QUIT_INTERVAL = 2500;
    private Dialog tipDialog = null;

    private int mYear;

    private SportCalendarAdapter adapter;
    private List<PathRecord> sportList = new ArrayList<>(0);

    private DataManager dataManager = null;

    private final int SPORT = 0x0012;
    @Override
    public int getLayoutId() {

        return R.layout.activity_home;
    }



    @Override
    public void initData(Bundle savedInstanceState) {
        mBinding= (ActivityHomeBinding) mBaseBinding;

        mBinding.tvTitle.setText("运动日历");

        dataManager = new DataManager(new RealmHelper());

        mYear = mBinding.calendarView.getCurYear();
        mBinding.tvYear.setText(String.valueOf(mYear));
        mBinding.tvMonthDay.setText(UIHelper.getString(R.string.date_month_day, mBinding.calendarView.getCurMonth(), mBinding.calendarView.getCurDay()));
        mBinding.tvLunar.setText("今日");
        mBinding.tvCurrentDay.setText(String.valueOf(mBinding.calendarView.getCurDay()));

        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mBinding.recyclerView.addItemDecoration(new SpaceItemDecoration(getResources().getDimensionPixelSize(R.dimen.line)));
        adapter = new SportCalendarAdapter(R.layout.adapter_sportcalendar, sportList);
        mBinding.recyclerView.setAdapter(adapter);

        mBinding.calendarView.setWeekStarWithSun();

        mBinding.calendarView.setWeekBar(CustomWeekBar.class);

        upDateUI();

    }

    @Override
    public void initListener() {

        mBinding.flCurrent.setOnClickListener(this);
        mBinding.tvMonthDay.setOnClickListener(this);
        mBinding.reRight.setOnClickListener(this);
        mBinding.reBack.setOnClickListener(this);
        mBinding.calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                mBinding.tvLunar.setVisibility(View.VISIBLE);
                mBinding.tvYear.setVisibility(View.VISIBLE);
                mBinding.tvMonthDay.setText(UIHelper.getString(R.string.date_month_day, calendar.getMonth(), calendar.getDay()));
                mBinding.tvYear.setText(String.valueOf(calendar.getYear()));
                mBinding.tvLunar.setText(calendar.getLunar());
                mYear = calendar.getYear();

                getSports(DateUtils.formatStringDateShort(calendar.getYear(), calendar.getMonth(), calendar.getDay()));

                LogUtils.d("onDateSelected", "  -- " + calendar.getYear() +
                        "  --  " + calendar.getMonth() +
                        "  -- " + calendar.getDay() +
                        "  --  " + isClick + "  --   " + calendar.getScheme());
            }
        });
        mBinding.calendarView.setOnYearChangeListener(year -> {
            mBinding.tvMonthDay.setText(String.valueOf(year));
        });
        adapter.setOnItemClickListener((adapter, view, position) -> {
            SportRecordDetailsActivity.StartActivity(this, sportList.get(position));
        });
    }

    //recyclerView设置间距
    protected class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int mSpace;

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.right = mSpace;
            outRect.left = mSpace;
            outRect.bottom = mSpace;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = mSpace;
            } else {
                outRect.top = 0;
            }

        }

        SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }

    private void upDateUI() {
        loadSportData();

        getSports(DateUtils.formatStringDateShort(mBinding.calendarView.getCurYear(), mBinding.calendarView.getCurMonth(), mBinding.calendarView.getCurDay()));
    }

    private void loadSportData() {
        try {
            List<SportMotionRecord> records = dataManager.queryRecordList(Integer.parseInt(SPUtils.getInstance().getString(MySp.USERID, "0")));
            if (null != records) {
                Map<String, Calendar> map = new HashMap<>();
                for (SportMotionRecord record : records) {
                    String dateTag = record.getDateTag();
                    String[] strings = dateTag.split("-");
                    int year = Integer.parseInt(strings[0]);
                    int month = Integer.parseInt(strings[1]);
                    int day = Integer.parseInt(strings[2]);
                    map.put(getSchemeCalendar(year, month, day, 0xFFCC0000, "记").toString(),
                            getSchemeCalendar(year, month, day, 0xFFCC0000, "记"));
                }
                //此方法在巨大的数据量上不影响遍历性能，推荐使用
                mBinding.calendarView.setSchemeDate(map);
            }
        } catch (Exception e) {
            LogUtils.e("获取运动数据失败", e);
        }
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        calendar.addScheme(new Calendar.Scheme());
//        calendar.addScheme(0xFF008800, text);
        return calendar;
    }

    private void getSports(String dateTag) {
        try {
            List<SportMotionRecord> records = dataManager.queryRecordList(Integer.parseInt(SPUtils.getInstance().getString(MySp.USERID, "0")), dateTag);
            if (null != records) {

                sportList.clear();
                adapter.notifyDataSetChanged();

                for (SportMotionRecord record : records) {
                    PathRecord pathRecord = new PathRecord();
                    pathRecord.setId(record.getId());
                    pathRecord.setDistance(record.getDistance());
                    pathRecord.setDuration(record.getDuration());
                    pathRecord.setPathline(MotionUtils.parseLatLngLocations(record.getPathLine()));
                    pathRecord.setStartpoint(MotionUtils.parseLatLngLocation(record.getStratPoint()));
                    pathRecord.setEndpoint(MotionUtils.parseLatLngLocation(record.getEndPoint()));
                    pathRecord.setStartTime(record.getmStartTime());
                    pathRecord.setEndTime(record.getmEndTime());
                    pathRecord.setCalorie(record.getCalorie());
                    pathRecord.setSpeed(record.getSpeed());
                    pathRecord.setDistribution(record.getDistribution());
                    pathRecord.setDateTag(record.getDateTag());
                    sportList.add(pathRecord);
                }
                if (sportList.isEmpty())
                    mBinding.sportAchievement.setVisibility(View.GONE);
                else
                    mBinding.sportAchievement.setVisibility(View.VISIBLE);
                adapter.notifyDataSetChanged();
            } else {
                mBinding.sportAchievement.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            LogUtils.e("获取运动数据失败", e);
            mBinding.sportAchievement.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.fl_current:
                mBinding.calendarView.scrollToCurrent();
                break;
            case R.id.tv_month_day:
                if (!mBinding.calendarLayout.isExpand()) {
                    mBinding.calendarLayout.expand();
                    return;
                }
                mBinding.calendarView.showYearSelectLayout(mYear);
                mBinding.tvLunar.setVisibility(View.GONE);
                mBinding.tvYear.setVisibility(View.GONE);
                mBinding.tvMonthDay.setText(String.valueOf(mYear));
                break;
            case R.id.reRight:
                startActivityForResult(new Intent(HomeActivity.this, SportsActivity.class), SPORT);
                break;
            case R.id.reBack:
                showTipDialog("退出登录",
                        "退出登录后将会删除历史数据,\n下次登录依然可以使用本账号!",
                        () -> logOut());
                break;
            default:
                break;
        }

    }


    private void showTipDialog(String title, String tips, TipCallBack tipCallBack) {
        tipDialog = new Dialog(context, R.style.matchDialog);
        View view = LayoutInflater.from(context).inflate(R.layout.tip_dialog_layout, null);
        ((TextView) (view.findViewById(R.id.title))).setText(title);
        ((TextView) (view.findViewById(R.id.tips))).setText(tips);
        view.findViewById(R.id.cancelTV).setOnClickListener(
                v -> tipDialog.dismiss());
        view.findViewById(R.id.confirmTV).setOnClickListener(v -> {
            tipCallBack.confirm();
            tipDialog.dismiss();
        });
        tipDialog.setContentView(view);
        tipDialog.show();
    }

    private interface TipCallBack {
        void confirm();
    }

    private void logOut() {
        SPUtils.getInstance().put(MySp.ISLOGIN, false);

        dataManager.deleteSportRecord();

        MyApplication.exitActivity();
        ToastUtils.showShort("退出登陆成功!");

        Intent it = new Intent(context, LoginActivity.class);
        context.startActivity(it);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) { // 表示按返回键 时的操作
                long backPressed = System.currentTimeMillis();
                if (backPressed - lastBackPressed > QUIT_INTERVAL) {
                    lastBackPressed = backPressed;
                    ToastUtils.showShort("再按一次退出");
                    return false;
                } else {
                    moveTaskToBack(false);
                    MyApplication.closeApp(this);
                    finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (null != dataManager)
            dataManager.closeRealm();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case SPORT:
                upDateUI();
                break;
            default:
                break;
        }
    }
}
